<template>
    <Container class="sync-list">
      <div class="container-header" slot="header">
        <Form class="search">
          <Row>
            <Col span="5">
              <FormItem label="物料名称">
                <Input v-model.trim="list1.form.materialName" @on-enter="onSearchBtnClick" placeholder="物料名称"/>
              </FormItem>
            </Col>
            <Col span="5">
              <FormItem label="物料品牌">
                <Input v-model.trim="list1.form.materialBrand" @on-enter="onSearchBtnClick" placeholder="物料品牌"/>
              </FormItem>
            </Col>
            <Col span="4">
              <FormItem label="物料规格">
                <Input v-model.trim="list1.form.materialSpec" @on-enter="onSearchBtnClick" placeholder="物料规格"/>
              </FormItem>
            </Col>
            <Col span="4">
              <FormItem label="物料花纹">
                <Input v-model.trim="list1.form.materialFigure" @on-enter="onSearchBtnClick" placeholder="物料花纹"/>
              </FormItem>
            </Col>
            <Col span="5">
              <FormItem label="物料层级">
                <Input v-model.trim="list1.form.materialLayer" @on-enter="onSearchBtnClick" placeholder="物料层级"/>
              </FormItem>
            </Col>
            <Col span="1" class-name="search small">
              <Button class="btn-search" type="primary" icon="ios-search" @click="onSearchBtnClick"></Button>
            </Col>
          </Row>
        </Form>
      </div>
        <Tabs v-model="tab" @on-click="onChangeTab">
          <Button 
            size="large" 
            class="item" 
            type="primary" 
            slot="extra"
            icon="md-more"
            v-show="tab === 'tab1'"
            @click="onBindProduct">批量绑定</Button>
          <Button 
            size="large" 
            class="item"
            slot="extra"
            icon="md-more"
            v-show="tab === 'tab1'"
            @click="onUnBindProduct">批量解绑</Button>
          <TabPane label="商品同步" name="tab1">
              <homeTable
                :list="list1"
                @getData="fillData(1)"
                @onPageSizeChange="onPageSizeChange"
                @onPageChange="onPageChange"
                @onSelectionChange="onSelectionChange"
              />
          </TabPane>
          <TabPane label="不需绑定商品" name="tab2">
              <homeTable
                :list="list2"
                @getData="fillData(2)"
                @onPageSizeChange="onPageSizeChange2"
                @onPageChange="onPageChange2"
              />
          </TabPane>
        </Tabs>
				<BindEditItem ref="bindEdit" @complete="fillData(1)"></BindEditItem>
    </Container>
</template>
<script>
import homeTable from "~/homeTable"
import SyncListData from "./list/SyncListData"
import SyncListData2 from "./list/SyncListData2"
import BindEditItem from "./edit/BindEditItem"
import { clearEmpty } from '@/util'
export default {
  name: 'product/sync/list',
	components: {
    homeTable,
		BindEditItem
	},
  data() {
    return {
      keyword: "",
      tab: 'tab1',
      list1: SyncListData,
      list2: SyncListData2,
      selection: []
    };
  },
  mounted() {
    // this.list.currentPage =  ~~this.$route.query.currentPage || 1
    // this.list.pageSize = ~~this.$route.query.pageSize || this.list.pageSize
    this.$bus.$on('onBind', ({row}) => this.onBind(row))
    this.$bus.$on('onNotBind', ({row}) => this.onNotBind(row))
    this.$bus.$on('onSwitch', ({row, type}) => this.onSwitch(row, type))
    this.$bus.$on('changeState', ({data, key}) => {
      if (data.length) {
        this.list1.isBind = data[0] === 1 ? false : true
      } else {
        this.list1.isBind = null
      }
      this.onSearchBtnClick()
    })
    this.fillData(1)
  },
  destroyed() {
    this.$bus.$off()
  },
  methods: {
    onSearchBtnClick() {
      if (this.tab === 'tab1') {
        this.list1.currentPage = 1
			  this.fillData(1)
      } else {
        this.list2.currentPage = 1
			  this.fillData(2)
      }
    },
    onChangeTab() {
      if (this.tab === 'tab1') this.fillData(1)
      if (this.tab === 'tab2') this.fillData(2)
    },
    fillData(type) {
      let param = {}
      if (type === 1) {
        param = {
          current: this.list1.currentPage,
          size: this.list1.pageSize,
          isBind: this.list1.isBind,
          isNeedBind: true
        }
      } else {
        param = {
          current: this.list2.currentPage,
          size: this.list2.pageSize,
          isNeedBind: false
        }
      }
      this.getData(param).then(data => {
        this.$nextTick(() => {
          this['list' + type].totalItem = data.total
          this['list' + type].data = []
          setTimeout(() => {
            this['list' + type].status = "pass"
            this.$set(this['list' + type], 'data', data.list)
          }, 10)
        })
      }).catch(() =>{
        this['list' + type].status = "error"
      })
    },
    getData(obj) {
      this.selection = []
			let param = {
        ...obj,
        name: this.keyword,
        materialName: this.list1.form.materialName,
        materialBrand: this.list1.form.materialBrand,
        materialSpec: this.list1.form.materialSpec,
        materialFigure: this.list1.form.materialFigure,
        materialLayer: this.list1.form.materialLayer
      }
      param = clearEmpty(param)
      if (this.tab === 'tab1') this.list1.status = "loading"
      if (this.tab === 'tab2') this.list2.status = "loading"
      return new Promise((resolve, reject) => {
        this.$ajaxGet("/product/erp_materiel/materiel/page", param).then(data => {
          let list = (data.records || []).map(item => {
            return {
              ...item,
              id: item.id,
              materialSn: item.materialSn,
              materialName: item.materialName,
              materialBrand: item.materialBrand,
              materialSpec: item.materialSpec,
              materialFigure: item.materialFigure,
              materialLayer: item.materialLayer,
              productCenterId: item.productCenterId,
              materialId: item.materialId
            }
          })
          resolve({total: Number(data.total), list: list})
        }).catch(() => {
          reject()
        })
      }) 
    },
    onSwitch(row, type) {
      let params = {
        materialId: row.materialId,
        needBind: !row.needBind
      }
      this.$jsonPost('/product/erp_materiel/binding/need', params).then(() => {
        this.$Notice.success({
          title: '操作成功'
        })
        if (type === 1) {
          this.fillData(1)
        } else {
          this.fillData(2)
        }
      }).catch(() => {
        if (type === 1) {
          this.fillData(1)
        } else {
          this.fillData(2)
        }
      })
    },
		onBind(row) {
			this.$refs.bindEdit.updateForm([row.materialId])
    },
    onNotBind(row) {
      this.unBind([row.materialId])
    },
    unBind(param) {
      this.$Modal.confirm({
        title: '解绑',
        content: '确定要解绑吗？',
        onOk: () => {
          this.$jsonPost('/product/erp_materiel/unBinding', param).then(() => {
            this.$Notice.success({
              title: '解绑成功'
            })
            this.fillData(1)
          })
        }
      })
    },
    onSelectionChange(selection) {
      this.selection = selection
    },
    onBindProduct() {
      if (this.selection.length === 0) {
        this.$Notice.warning({
          title: '请先选择要绑定的物料'
        })
        return
      }
      let materialIds = this.selection.filter(item => !item.productCenterId).map(item => item.materialId)
      if (materialIds.length === 0) {
        this.$Notice.warning({
          title: '提示',
          desc: '您选择的物料全是已绑定的，请重新选择'
        })
        return
      }
      let flag = this.selection.every(item => !item.productCenterId)
      if (!flag) {
        this.$Notice.warning({
          title: '提示',
          desc: '您选择的物料中有已绑定的哦，将不会对已绑定的物料做操作~~~'
        })
      }
      if (materialIds.length) this.$refs.bindEdit.updateForm(materialIds)
    },
    onUnBindProduct() {
      if (this.selection.length === 0) {
        this.$Notice.warning({
          title: '请先选择要解绑的物料'
        })
        return
      }
      let materialIds = this.selection.filter(item => item.productCenterId).map(item => item.materialId)
      if (materialIds.length === 0) {
        this.$Notice.warning({
          title: '提示',
          desc: '您选择的物料全是未解绑的物料，请重新选择'
        })
        return
      }
      let flag = this.selection.every(item => item.productCenterId)
      if (!flag) {
        this.$Notice.warning({
          title: '提示',
          desc: '您选择的物料中有未绑定的物料哦，将不会对未绑定的物料做操作~~~'
        })
      }
      this.unBind(materialIds)
    },
    onPageChange(number) {
			this.list1.currentPage = number
			this.$router.push({
				name: "product/sync/list",
				query: {
					currentPage: this.list1.currentPage,
					pageSize: this.list1.pageSize
				}
			});
      this.fillData(1)
		},
    onPageSizeChange(pageSize) {
			this.list1.currentPage = 1
			this.list1.pageSize = pageSize
			this.$router.push({
				name: "product/sync/list",
				query: {
					currentPage: this.list1.currentPage,
					pageSize: this.list1.pageSize
				}
			});
			this.fillData(1)
    },
    onPageChange2(number) {
			this.list2.currentPage = number
			this.$router.push({
				name: "product/sync/list"
			});
      this.fillData(2)
		},
    onPageSizeChange2(pageSize) {
			this.list2.currentPage = 1
			this.list2.pageSize = pageSize
			this.$router.push({
				name: "product/sync/list"
			})
			this.fillData(2)
		}
	}
	// watch: {
	// 	$route() {
	// 		let page = ~~this.$route.query.currentPage
	// 		let table = this.list
	// 		if (table.currentPage !== page) {
	// 			table.currentPage = ~~this.$route.query.currentPage === 0 ? 1 : ~~this.$route.query.currentPage
	// 			this.getData()
	// 		}
	// 	}
	// }
};
</script>
